package com.wuage.application.impl;

import com.wuage.application.IEmailService;
import com.wuage.application.IUacAccountService;
import com.wuage.domain.model.UacAccount;
import com.wuage.infrastructure.exception.BizException;
import com.wuage.infrastructure.status.BizResultCode;
import com.wuage.infrastructure.utils.JwtUtils;
import com.wuage.infrastructure.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author Shynin
 * @version 1.0
 * @date 2020-09-13 14:42
 */
@Slf4j
@Service
public class EmailServiceImpl implements IEmailService {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;
    @Value("${deploy.host}")
    private String host;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private IUacAccountService accountService;

    @Override
    public Boolean sendAuthEmail(String email) {
        Long id = JwtUtils.getLoginUser().getId();
        UacAccount account = accountService.getById(id);
        if(account.getEmailAuthentication()) {
            throw new BizException(BizResultCode.EMAIL_CHECKED);
        }
        MimeMessage message = javaMailSender.createMimeMessage();
        String emailContent = getEmailContent(host, id, email);
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject("主题：邮箱激活");
            helper.setText(emailContent, true);

            javaMailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        redisUtils.set(email, id, 60 * 60 * 3);
        return true;
    }

    public String getEmailContent(String host, Long userId, String email) {
        String content = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "<meta charset=\"UTF-8\">\n" +
                "<title>account active</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "<p>您好, 请点击下面链接激活您的账号！</p><br/> \n" +
                "<a href=\"" + host + "/account/email/authentication/" + userId +"/" + email +"\">激活账号</a>\n" +
                "</body>\n" +
                "</html>";
        return content;
    }
}
